package com.strelitzia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.strelitzia.dao.DynamicDao;
import com.strelitzia.entity.*;
import com.strelitzia.exception.StrelitziaException;
import com.strelitzia.filter.CorsFilter;
import com.strelitzia.service.*;
import com.strelitzia.utils.FileUtil;
import com.strelitzia.utils.TimeUtil;
import com.strelitzia.vo.DynamicForm;
import com.strelitzia.vo.DynamicItem;
import com.strelitzia.vo.UploadFrom;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @create 2023/12/25 10:22
 */
@Service
public class DynamicServiceImpl extends ServiceImpl<DynamicDao, DynamicEntity> implements DynamicService {
    @Autowired
    private UserService userService;
    @Autowired
    private FriendsService friendsService;

    @Autowired
    private ReviewService reviewService;

    @Autowired
    private AlbumService albumService;

    @Autowired
    private PhotoService photoService;

    @Autowired
    private NotificationService notificationService;

    @Override
    public void add(DynamicForm dynamicForm) {
        DynamicEntity dynamicEntity = new DynamicEntity();
        BeanUtils.copyProperties(dynamicForm, dynamicEntity);
        StringBuilder attachments = new StringBuilder();

        AlbumEntity album = albumService.getOne(new QueryWrapper<AlbumEntity>().eq("album_name", "动态相册").eq("uid", CorsFilter.loginUserId.get()));
        if (album == null) {
            albumService.create("动态相册");
            album = albumService.getOne(new QueryWrapper<AlbumEntity>().eq("album_name", "动态相册").eq("uid", CorsFilter.loginUserId.get()));
        }

        if (dynamicForm.getFiles() != null && dynamicForm.getFiles().length > 0) {
            Timestamp timestamp = new Timestamp(new Date().getTime());
            for (MultipartFile file : dynamicForm.getFiles()) {
                String src = FileUtil.fileUp(file);
                PhotoEntity photoEntity = new PhotoEntity();
                photoEntity.setAlbumName(album.getAlbumName());
                photoEntity.setSrc(src);
                photoEntity.setDelTag(0);
                photoEntity.setUid(CorsFilter.loginUserId.get());
                photoEntity.setAlbumId(album.getId());
                photoEntity.setUploadTime(timestamp);
                photoService.save(photoEntity);
                album.setUpdateTime(photoEntity.getUploadTime());
                albumService.updateById(album);
                attachments.append(src).append(",");

            }
            attachments.delete(attachments.length() - 1, attachments.length());
        }


        dynamicEntity.setAttachments(attachments.toString());
        dynamicEntity.setPublishTime(new Timestamp(new Date().getTime()));
        dynamicEntity.setLikes(0);
        dynamicEntity.setLikeIds("");
        this.save(dynamicEntity);
    }

    @Override
    public List<DynamicItem> getList() {
        List<DynamicEntity> list = this.list(new QueryWrapper<DynamicEntity>()
                .eq("status", 1)
                .orderByDesc("publish_time"));
        return getDynamicItems(list);
    }

    @Override
    public List<DynamicItem> getList(Integer id) {
        List<DynamicEntity> list = this.list(new QueryWrapper<DynamicEntity>()
                .eq("status", 1)
                .eq("uid", id)
                .orderByDesc("publish_time"));
        return getDynamicItems(list);
    }

    @Override
    public List<DynamicItem> getListForFriend() {
        Integer id = CorsFilter.loginUserId.get();
        List<DynamicEntity> list = this.baseMapper.getListForFriend(id);
        return getDynamicItems( list);
    }

    @Override
    public void like(Integer did) throws StrelitziaException {
        DynamicEntity dynamicEntity = this.getById(did);
        if (dynamicEntity != null) {
            dynamicEntity.setLikes(dynamicEntity.getLikes() + 1);
            dynamicEntity.setLikeIds(dynamicEntity.getLikeIds() + "[" + CorsFilter.loginUserId.get() + "]");
            NotificationEntity notificationEntity = new NotificationEntity();
            notificationEntity.setAppend(did);
            notificationEntity.setMessage("点赞了你的动态");
            notificationEntity.setNotifier(CorsFilter.loginUserId.get());
            notificationEntity.setReceiver(dynamicEntity.getUid());
            notificationEntity.setType(0);
            notificationEntity.setTime(new Timestamp(new Date().getTime()));
            if (!notificationEntity.getReceiver().equals(notificationEntity.getNotifier())) {
                this.notificationService.save(notificationEntity);
            }

            this.updateById(dynamicEntity);
        } else {
            throw new StrelitziaException("该动态已删除");
        }
    }

    @Override
    public void unlike(Integer did) throws StrelitziaException {
        DynamicEntity dynamicEntity = this.getById(did);
        if (dynamicEntity != null) {
            dynamicEntity.setLikes(dynamicEntity.getLikes() - 1);
            dynamicEntity.setLikeIds(dynamicEntity.getLikeIds().replace("[" + CorsFilter.loginUserId.get() + "]", ""));
            this.updateById(dynamicEntity);
        } else {
            throw new StrelitziaException("该动态已删除");
        }
    }

    @Override
    public DynamicItem getDynamic(Integer did) throws StrelitziaException {
        DynamicEntity item = this.getById(did);
        if (item != null) {
            DynamicItem dynamicItem = new DynamicItem();
            dynamicItem.setUid(item.getUid());
            dynamicItem.setLikes(item.getLikes());
            dynamicItem.setContent(item.getContent());
            dynamicItem.setIsLiked(item.getLikeIds().contains("[" + CorsFilter.loginUserId.get() + "]"));
            dynamicItem.setTime(TimeUtil.formattingTime(item.getPublishTime()));
            if (!StringUtils.isNullOrEmpty(item.getAttachments())) {
                String[] split = item.getAttachments().split(",");
                for (int i = 0; i < split.length; i++) {
                    split[i] = "/api/res/" + split[i];
                }
                dynamicItem.setAttachments(split);
            } else {
                dynamicItem.setAttachments(new String[]{});
            }
            dynamicItem.setReview_list(reviewService.getAllForHot(item.getId()));
            dynamicItem.setId(item.getId());
            UserEntity byId = userService.getById(item.getUid());
            dynamicItem.setAvatar("/api/res/" + byId.getAvatar());
            FriendsEntity one = friendsService.getOne(new QueryWrapper<FriendsEntity>().eq("uid", CorsFilter.loginUserId.get()).eq("friend_id", item.getUid()));
            dynamicItem.setNickname(byId.getNickname());
            dynamicItem.setIsFriend(false);
            if (one != null) {
                dynamicItem.setIsFriend(true);
                if (!StringUtils.isNullOrEmpty(one.getRemark())) {
                    dynamicItem.setNickname(one.getRemark());
                }
            }
            return dynamicItem;
        }
        throw new StrelitziaException("该动态已删除");
    }

    @Override
    public List<DynamicItem> getListForMe() {
        QueryWrapper<DynamicEntity> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("uid", CorsFilter.loginUserId.get());
        objectQueryWrapper.orderByDesc("publish_time");
//        Integer id = CorsFilter.loginUserId.get();
        List<DynamicEntity> list = this.list(objectQueryWrapper);
        return getDynamicItems(list);
    }

    @Override
    public void del(Integer id) {
        List<ReviewEntity> reviewEntities = reviewService.list(new QueryWrapper<ReviewEntity>().eq("review_id", id).eq("type", 1));
        if (reviewEntities != null) {
            for (ReviewEntity reviewEntity : reviewEntities) {
                reviewService.del(reviewEntity.getId());
            }
        }
        this.removeById(id);
    }

    @Override
    public List<DynamicItem> getListForSearch(String keyword) {
//        Integer id = CorsFilter.loginUserId.get();
        List<DynamicEntity> list = this.list(new QueryWrapper<DynamicEntity>()
                .like("content", keyword)
                .eq("status", 1)
                .orderByDesc("publish_time"));
        return getDynamicItems(list);
    }

    private List<DynamicItem> getDynamicItems(List<DynamicEntity> list) {
        if (list != null) {
            return list.stream().map(item -> {
                DynamicItem dynamicItem = new DynamicItem();
                dynamicItem.setUid(item.getUid());
                dynamicItem.setLikes(item.getLikes());
                dynamicItem.setStatus(item.getStatus());
                dynamicItem.setContent(item.getContent());
                dynamicItem.setIsLiked(item.getLikeIds().contains("[" + CorsFilter.loginUserId.get().toString() + "]"));
                dynamicItem.setTime(TimeUtil.formattingTime(item.getPublishTime()));
                if (!StringUtils.isNullOrEmpty(item.getAttachments())) {
                    String[] split = item.getAttachments().split(",");
                    for (int i = 0; i < split.length; i++) {
                        split[i] = "/api/res/" + split[i];
                    }
                    dynamicItem.setAttachments(split);
                } else {
                    dynamicItem.setAttachments(new String[]{});

                }
                dynamicItem.setReview_list(reviewService.getTop3ForHot(item.getId()));
                dynamicItem.setId(item.getId());
                UserEntity byId = userService.getById(item.getUid());
                dynamicItem.setAvatar("/api/res/" + byId.getAvatar());
                FriendsEntity one = friendsService.getOne(new QueryWrapper<FriendsEntity>().eq("uid", CorsFilter.loginUserId.get()).eq("friend_id", item.getUid()));
                dynamicItem.setNickname(byId.getNickname());
                dynamicItem.setIsFriend(false);
                if (one != null) {
                    dynamicItem.setIsFriend(true);
                    if (!StringUtils.isNullOrEmpty(one.getRemark())) {
                        dynamicItem.setNickname(one.getRemark());
                    }
                }
                return dynamicItem;
            }).collect(Collectors.toList());
        }
        return null;
    }
}
